<?php

namespace App\Logging\Service;

class LogJobService
{
    const PATH_MODE_GENERAL = 'general';
    const PATH_MODE_CLASS = 'class';

    /**
     * @var static 单例模式
     */
    protected static $instance;

    /**
     * 单例模式
     */
    public static function getInstance()
    {
        if (static::$instance instanceof static) {
            return static::$instance;
        }
        static::$instance = new static();
        return static::$instance;
    }

    protected $jobName = ''; // job 名
    protected $jobClass = ''; // job 类
    protected $jobUuid = ''; // job uuid
    protected $extra = []; // 额外参数

    /**
     * @return mixed
     */
    public function getJobName()
    {
        return $this->jobName;
    }

    /**
     * @param mixed $cmdName
     */
    public function setJobName($cmdName)
    {
        $this->jobName = $cmdName;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getJobClass()
    {
        return $this->jobClass;
    }

    /**
     * @param mixed $cmdClass
     */
    public function setJobClass($cmdClass)
    {
        $this->jobClass = $cmdClass;
        return $this;
    }

    public function getJobUuid(): string
    {
        return $this->jobUuid;
    }

    public function setJobUuid(string $jobUuid)
    {
        $this->jobUuid = $jobUuid;
        return $this;
    }

    public function getExtra(): array
    {
        return $this->extra;
    }

    public function setExtra(array $extra)
    {
        $this->extra = $extra;
        return $this;
    }

    /**
     * 追加额外信息
     * @param $key
     * @param $value
     * @return $this
     * @author Chris Yu <chrisyu@crabapple.top> 2024/11/13
     */
    public function appendExtra($key, $value)
    {
        $this->extra[$key] = $value;
        return $this;
    }

    /**
     * 基于模式生成日志子目录
     * @param $mode
     * @return string
     * @author Chris Yu <chrisyu@crabapple.top> 2024/11/8
     */
    public function generateJobLogSubDir($mode): string
    {
        if ($mode === self::PATH_MODE_CLASS) {
            return $this->generateJobLogSubDirBaseClass();
        }
        return '';
    }

    protected function generateJobLogSubDirBaseClass()
    {
        if (!$this->getJobClass()) {
            return '';
        }

        $subDir = str_replace('\\', '/', $this->getJobClass());
        $subDir = str_replace(['App/', 'Jobs/'], ['', ''], $subDir);

        return $subDir;
    }
}
